﻿// The MIT License (MIT)
// Copyright (c) 2014 Grégory Ghez
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace JenkinsController.Tests.Model
{
    using System;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Jenkins.Core;
    using Jenkins.Domain;
    using JenkinsController.Framework;
    using JenkinsController.Model;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    using Ploeh.AutoFixture;

    [TestClass]
    public class DataServiceTests
    {
        private readonly Fixture defaultFixture = new Fixture();

        private CollectionHelper collectionHelper;
        private IDataService defaultDataService;
        private Mock<IJenkinsRestClient> restClient;

        [TestInitialize]
        public void InitContext()
        {
            this.collectionHelper = new CollectionHelper();
            this.restClient = new Mock<IJenkinsRestClient>();
            this.defaultDataService = new DataService(this.collectionHelper, this.restClient.Object);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Invoke_Constructor_WithNullCollectionHelper_ShouldFailed()
        {
            new DataService(null, this.restClient.Object);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Invoke_Constructor_WithNullRestManager_ShouldFailed()
        {
            new DataService(this.collectionHelper, null);
        }

        [TestMethod]
        public void Invoke_RunJob_WithNullJob_ShouldNotCall_RunJobAsync()
        {
            this.defaultDataService.RunJobAsync(null).Wait();

            this.restClient.Verify(m => m.RunJobAsync(It.IsAny<JenkinsJob>()), Times.Never);
        }

        [TestMethod]
        public void Invoke_RunJob_ShouldCall_RunJobAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();
            this.defaultDataService.RunJobAsync(job).Wait();

            this.restClient.Verify(m => m.RunJobAsync(It.Is<JenkinsJob>(j => Equals(j, job))), Times.Once);
        }

        [TestMethod]
        public void Invoke_StopJob_WithNullJob_ShouldNotCall_StopJobAsync()
        {
            this.defaultDataService.StopJobAsync(null).Wait();

            this.restClient.Verify(m => m.StopJobAsync(It.IsAny<JenkinsJob>()), Times.Never);
        }

        [TestMethod]
        public void Invoke_StopJob_ShouldCall_StopJobAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();

            this.restClient.Setup(m => m.GetJobAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsJob>();
                    tcs.SetResult(job);
                    return tcs.Task;
                });

            this.defaultDataService.StopJobAsync(job).Wait();

            this.restClient.Verify(m => m.GetJobAsync(It.Is<string>(url => string.Equals(url, job.RestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(d => !d)), Times.Exactly(5));

            this.restClient.Verify(m => m.StopJobAsync(It.Is<JenkinsJob>(j => Equals(j, job))), Times.Once);
        }

        [TestMethod]
        public void Invoke_StopJob_WithNullUpdate_ShouldNotCall_StopJobAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();

            this.restClient.Setup(m => m.GetJobAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsJob>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });

            this.defaultDataService.StopJobAsync(job).Wait();

            this.restClient.Verify(m => m.GetJobAsync(It.Is<string>(url => string.Equals(url, job.RestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(d=>!d)), Times.Once);

            this.restClient.Verify(m => m.StopJobAsync(It.Is<JenkinsJob>(j => Equals(j, job))), Times.Never);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithNullServer_ShouldNotCall_GetServerAsync()
        {
            this.defaultDataService.UpdateAsync(null as JenkinsServer).Wait();

            this.restClient.Verify(m => m.GetServerAsync(It.IsAny<string>()), Times.Never);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithNullUpdate_ShouldNotUpdate()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            var initServer = new JenkinsServer();
            foreach (PropertyInfo prop in typeof(JenkinsServer).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                prop.SetValue(initServer, prop.GetValue(server));
            }

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            foreach (PropertyInfo prop in typeof(JenkinsServer).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                Assert.AreEqual(prop.GetValue(initServer), prop.GetValue(server));
            }
        }

        [TestMethod]
        public void Invoke_UpdateServer_OnNullNode_ShouldReplace_Node()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            server.Node = null;
            var upadte = new JenkinsServer { Node = this.defaultFixture.Create<JenkinsNode>() };

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(upadte);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            Assert.AreSame(upadte.Node, server.Node);
        }

        [TestMethod]
        public void Invoke_UpdateServer_ShouldCall_GetServerAsync()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            var update = this.defaultFixture.Create<JenkinsServer>();

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            this.restClient.Verify(m => m.GetServerAsync(It.Is<string>(url => string.Equals(url, server.Url, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(d=>!d)), Times.Once);

            Assert.AreNotSame(update.Node, server.Node);

            Assert.AreEqual(update.Node.Description, server.Node.Description);
            Assert.AreEqual(update.Node.IsQuietingDown, server.Node.IsQuietingDown);
            Assert.AreEqual(update.Node.Mode, server.Node.Mode);
            Assert.AreEqual(update.Node.NodeDescription, server.Node.NodeDescription);
            Assert.AreEqual(update.Node.NodeName, server.Node.NodeName);
            Assert.AreEqual(update.Node.NumExecutors, server.Node.NumExecutors);
            Assert.AreEqual(update.Node.UseSecurity, server.Node.UseSecurity);
            Assert.AreSame(update.Node.Jobs, server.Node.Jobs);
            Assert.AreSame(update.Node.Views, server.Node.Views);
            Assert.AreSame(update.Node.PrimaryView, server.Node.PrimaryView);
            Assert.AreSame(update.Users, server.Users);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithInitialNullNode_ShouldSetUpdatedServerNode()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            server.Node = null;
            var update = this.defaultFixture.Create<JenkinsServer>();

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            Assert.AreSame(update.Node, server.Node);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithSameUpdatedJobs_ShouldNotChange_JobsProperty()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            var update = this.defaultFixture.Create<JenkinsServer>();

            update.Node.Jobs = server.Node.Jobs.ToArray();

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            Assert.AreNotSame(update.Node.Jobs, server.Node.Jobs);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithSameUpdatedViews_ShouldNotChange_ViewsProperty()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            var update = this.defaultFixture.Create<JenkinsServer>();

            update.Node.Views = server.Node.Views.ToArray();

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            Assert.AreNotSame(update.Node.Views, server.Node.Views);
        }

        [TestMethod]
        public void Invoke_UpdateServer_WithSameUpdatedUsers_ShouldNotChange_UsersProperty()
        {
            var server = this.defaultFixture.Create<JenkinsServer>();
            var update = this.defaultFixture.Create<JenkinsServer>();

            update.Users = server.Users.ToArray();

            this.restClient.Setup(m => m.GetServerAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsServer>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(server).Wait();

            Assert.AreNotSame(update.Users, server.Users);
        }

        [TestMethod]
        public void Invoke_UpdateBuild_ShouldCall_GetBuildAsync()
        {
            var build = this.defaultFixture.Create<JenkinsBuild>();
            var update = this.defaultFixture.Create<JenkinsBuild>();

            this.restClient.Setup(m => m.GetBuildAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsBuild>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(build).Wait();

            this.restClient.Verify(m => m.GetBuildAsync(It.Is<string>(url => string.Equals(url, build.RestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(d => d)), Times.Once);

            CollectionAssert.AreEquivalent(update.Artifacts, build.Artifacts);
            Assert.AreEqual(update.TestReport, build.TestReport);
            Assert.AreEqual(update.ChangeSet, build.ChangeSet);
            Assert.AreEqual(update.DisplayName, build.DisplayName);
            Assert.AreEqual(update.Duration, build.Duration);
            Assert.AreEqual(update.EstimatedDuration, build.EstimatedDuration);
            Assert.AreEqual(update.Id, build.Id);
            Assert.AreEqual(update.IsBuilding, build.IsBuilding);
            Assert.AreEqual(update.Number, build.Number);
            Assert.AreEqual(update.Status, build.Status);
            Assert.AreEqual(update.TimeStamp, build.TimeStamp);
        }

        [TestMethod]
        public void Invoke_UpdateBuild_WithSameUpdatedArtifacts_ShouldNotChange_ArtifactsProperty()
        {
            var build = this.defaultFixture.Create<JenkinsBuild>();
            var update = this.defaultFixture.Create<JenkinsBuild>();

            update.Artifacts = build.Artifacts.ToArray();

            this.restClient.Setup(m => m.GetBuildAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsBuild>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(build).Wait();

            Assert.AreNotSame(update.Artifacts, build.Artifacts);
        }

        [TestMethod]
        public void Invoke_UpdateBuild_WithNullUpdate_ShouldNotUpdate()
        {
            var build = this.defaultFixture.Create<JenkinsBuild>();
            var initBuild = new JenkinsBuild();
            foreach (PropertyInfo prop in typeof(JenkinsBuild).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                prop.SetValue(initBuild, prop.GetValue(build));
            }

            this.restClient.Setup(m => m.GetBuildAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsBuild>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(build).Wait();

            foreach (PropertyInfo prop in typeof(JenkinsBuild).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                Assert.AreEqual(prop.GetValue(initBuild), prop.GetValue(build));
            }
        }

        [TestMethod]
        public void Invoke_UpdateBuild_WithNullBuild_ShouldNotCall_GetBuildAsync()
        {
            this.defaultDataService.UpdateAsync(null as JenkinsBuild).Wait();

            this.restClient.Verify(m => m.GetBuildAsync(It.IsAny<string>()), Times.Never);
        }

        [TestMethod]
        public void Invoke_UpdateView_WithNullView_ShouldNotCall_GetViewAsync()
        {
            this.defaultDataService.UpdateAsync(null as JenkinsView).Wait();

            this.restClient.Verify(m => m.GetViewAsync(It.IsAny<string>()), Times.Never);
        }

        [TestMethod]
        public void Invoke_UpdateView_WithNullUpdate_ShouldNotUpdate()
        {
            var view = this.defaultFixture.Create<JenkinsView>();
            var initView = new JenkinsView();
            foreach (PropertyInfo prop in typeof(JenkinsView).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                prop.SetValue(initView, prop.GetValue(view));
            }

            this.restClient.Setup(m => m.GetViewAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsView>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(view).Wait();

            this.restClient.Verify(c => c.GetJobAsync(It.IsAny<string>(), It.IsAny<bool>()), Times.Never);

            foreach (PropertyInfo prop in typeof(JenkinsView).GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                Assert.AreEqual(prop.GetValue(initView), prop.GetValue(view));
            }
        }

        [TestMethod]
        public void Invoke_UpdateView_ShouldCall_GetViewAsync()
        {
            var view = this.defaultFixture.Create<JenkinsView>();
            var update = this.defaultFixture.Create<JenkinsView>();

            this.restClient.Setup(m => m.GetViewAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsView>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(view).Wait();

            this.restClient.Verify(m => m.GetViewAsync(It.Is<string>(url => string.Equals(url, view.DetailsUrl, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(d=>!d)), Times.Once);
            //this.restClient.Verify(s => s.GetJobAsync(It.IsAny<string>(), It.Is<bool>(d=>!d)), Times.Exactly(update.Jobs.Length));

            Assert.AreEqual(update.Description, view.Description);
            CollectionAssert.AreEquivalent(update.Jobs, view.Jobs);
        }

        [TestMethod]
        public void Invoke_UpdateJob_ShouldCall_GetJobAsync_And_GetBuildAsync()
        {
            var update = this.defaultFixture.Create<JenkinsJob>();
            var buildUpdate = this.defaultFixture.Create<JenkinsBuild>();

            this.restClient.Setup(m => m.GetJobAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsJob>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.restClient.Setup(m => m.GetBuildAsync(It.IsAny<string>(), It.IsAny<bool>()))
               .Returns(() =>
               {
                   var tcs = new TaskCompletionSource<JenkinsBuild>();
                   tcs.SetResult(buildUpdate);
                   return tcs.Task;
               });

            var job = this.defaultFixture.Create<JenkinsJob>();
            this.defaultDataService.UpdateAsync(job).Wait();

            this.restClient.Verify(r => r.GetJobAsync(It.Is<string>(u => string.Equals(u, job.RestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<bool>(b => !b)), Times.Once);
            this.restClient.Verify(r => r.GetBuildAsync(It.IsAny<string>(), It.Is<bool>(b => b)), Times.Never);
            this.restClient.Verify(r => r.GetBuildAsync(It.IsAny<string>(), It.Is<bool>(b => !b)), Times.Exactly(3));

            Assert.AreEqual(update.Buildable, job.Buildable);
            CollectionAssert.AreEquivalent(update.Builds, job.Builds);
            Assert.AreEqual(update.Description, job.Description);
            Assert.AreEqual(update.DisplayName, job.DisplayName);
            Assert.AreEqual(update.IsInQueue, job.IsInQueue);

            Assert.AreSame(buildUpdate, job.LastBuild);
            Assert.AreSame(buildUpdate, job.LastCompletedBuild);
            Assert.AreSame(buildUpdate, job.LastFailedBuild);
            Assert.AreSame(update.LastStableBuild, job.LastStableBuild);
            Assert.AreSame(update.LastSuccessfulBuild, job.LastSuccessfulBuild);
            Assert.AreSame(update.LastUnstableBuild, job.LastUnstableBuild);
            Assert.AreSame(update.LastUnsuccessfulBuild, job.LastUnsuccessfulBuild);

            Assert.AreEqual(update.Name, job.Name);
            Assert.AreEqual(update.NextBuildNumber, job.NextBuildNumber);
            Assert.AreSame(update.Status, job.Status);
        }

        [TestMethod]
        public void Invoke_UpdateJob_WithSameUpdatedBuilds_ShouldNotChange_BuildsProperty()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();
            var update = this.defaultFixture.Create<JenkinsJob>();

            update.Builds = job.Builds.ToArray();

            this.restClient.Setup(m => m.GetJobAsync(It.IsAny<string>(), It.IsAny<bool>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsJob>();
                    tcs.SetResult(update);
                    return tcs.Task;
                });

            this.defaultDataService.UpdateAsync(job).Wait();

            Assert.AreNotSame(update.Builds, job.Builds);
        }
    }
}